package com.itxh.core.handler.statement;

import com.itxh.core.config.BoundSql;
import com.itxh.core.config.MappedStatement;

import java.sql.*;
import java.util.List;

public class PreparedStatementHandler implements StatementHandler {
    private ResultSetHandler resultSetHandler ;
    private ParameterHandler parameterHandler;

    public PreparedStatementHandler() {
        resultSetHandler = new DefaultResultSetHandler();
        parameterHandler = new DefaultParameterHandler();
    }

    @Override
    public Statement prepare(Connection connection, String sql)  throws Exception{
        try {
            return connection.prepareStatement(sql);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return null;
    }

    @Override
    public void parameterize(Statement statement, Object param, BoundSql boundSql) throws Exception{
        PreparedStatement preparedStatement = (PreparedStatement) statement;
        parameterHandler.setParameter(preparedStatement,param,boundSql);
    }

    @Override
    public <T> List<T> query(Statement statement, BoundSql boundSql, MappedStatement mappedStatement)  throws Exception{
        PreparedStatement preparedStatement = (PreparedStatement) statement;
        ResultSet rs = preparedStatement.executeQuery();
        return resultSetHandler.handleResultSet(rs,mappedStatement);

    }
}
